const app = getApp()
const uploadOss = require('../../utils/upload/uploadImg.js')
import { saveFile, getSearchHistory, getSearchMaterial, getSearchCase, getSearchSupplier, deleteHistory } from '../../api/index'

Page({
  data: {
    value: '',
    hasMoreBtn: false,
    sliceIndex: 0,
    sliceHotIndex: 0,
    active: 0,
    isSearch: false,
    isFocus: false,
    isCamera: false,
    keyword: '',
    historys: [],
    copyHistorys: [],
    hotHistorys: [],
    copyHotHistorys: [],
    materialPage: 1,
    casePage: 1,
    supplierPage: 1,
    pageSize: 10,
    materialList: [],
    materialNum: 0,
    caseList: [],
    caseNum: 0,
    supplierList: [],
    supplierNum: 0,
    isMaterialEmpty: false,
    isCaseEmpty: false,
    isSupplierEmpty: false,
    showMoreBtn: false,
    historyMoreBtn: false,
    showHistoryMoreBtn: false,
    hotMoreBtn: false,
    showHotMoreBtn: false,
    activeTab: 'material'
  },
  async delHistory () {
    try {
      await deleteHistory()
      wx.showToast({ title: '删除成功！', icon: 'none' })
      this.setData({ historys: [] })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  toggleShowMore () {
    if (this.data.sliceIndex > 0 && !this.data.historyMoreBtn) {
      this.data.historys = this.data.copyHistorys.slice(0, this.data.sliceIndex)
      this.setData({ historys: this.data.historys, historyMoreBtn: true })
    } else {
      this.setData({ historys: this.data.copyHistorys, historyMoreBtn: false })
    }
  },
  toggleHotShowMore () {
    if (this.data.sliceHotIndex > 0 && !this.data.hotMoreBtn) {
      this.data.hotHistorys = this.data.copyHotHistorys.slice(0, this.data.sliceHotIndex)
      this.setData({ hotHistorys: this.data.hotHistorys, hotMoreBtn: true })
    } else {
      this.setData({ hotHistorys: this.data.copyHotHistorys, hotMoreBtn: false })
    }
  },
  focusInput () {
    this.setData({ isFocus: true })
  },
  seeSupplier ({ currentTarget: { dataset: { item } } }) {
    wx.$nav.navigateTo(`/pages/supplier/index/index?id=${item.id}&name=${item.companyName}`)
  },
  selectKeyword ({ currentTarget: { dataset: { keyword } } }) {
    this.setData({ keyword: keyword, isSearch: true })
    this.getMaterialList()
    this.getCaseList()
    this.getSupplierList()
  },
  confirmSearch ({ detail: { value } }) {
    this.setData({
      materialList: [],
      caseList: [],
      supplierList: [],
      isFocus: false,
      keyword: value
    })
    if (value) {
      this.setData({ isSearch: true })
      this.getMaterialList()
      this.getCaseList()
      this.getSupplierList()
    } else {
      this.setData({
        materialList: [],
        caseList: [],
        supplierList: [],
        isSearch: false
      })
    }
  },
  changeTab ({ detail }) {
    this.setData({ activeTab: detail.name })
  },
  loadMore ({ currentTarget: { dataset: { key } } }) {
    if (key === 'material') {
      this.loadMaterialMore()
    } else if (key === 'case') {
      this.loadCaseMore()
    } else if (key === 'supplier') {
      this.loadSupplierMore()
    }
  },
  async loadMaterialMore () {
    try {
      if (this.materialLoading || this.materialAlloaded) return
      this.materialLoading = true
      let query = {
        currentPage: this.data.materialPage,
        pageLines: this.data.pageSize,
      }
      if (this.data.keyword) query.data = this.data.keyword
      const { ResultSet } = await getSearchMaterial({ ...query })
      this.materialAlloaded = !ResultSet.userData.data.length
      this.data.isMaterialEmpty = !ResultSet.userData.data.length
      this.setData({ isMaterialEmpty: this.data.isMaterialEmpty })
      if (ResultSet.userData.data.length) {
        this.data.materialPage = this.data.materialPage + 1
        this.data.materialList.push(...ResultSet.userData.data)
        this.setData({
          materialList: this.data.materialList,
          materialPage: this.data.materialPage
        })
      }
      this.materialLoading = false
    } catch (err) {
      this.materialLoading = false
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async loadCaseMore () {
    try {
      if (this.caseLoading || this.caseAlloaded) return
      this.caseLoading = true
      let query = {
        currentPage: this.data.casePage,
        pageLines: this.data.pageSize,
      }
      if (this.data.keyword) query.data = this.data.keyword
      const { ResultSet } = await getSearchCase({ ...query })
      this.caseAlloaded = !ResultSet.userData.data.length
      this.data.isCaseEmpty = !ResultSet.userData.data.length
      this.setData({ isCaseEmpty: this.data.isCaseEmpty })
      if (ResultSet.userData.data.length) {
        this.data.casePage = this.data.casePage + 1
        this.data.caseList.push(...ResultSet.userData.data)
        this.setData({
          caseList: this.data.caseList,
          casePage: this.data.casePage
        })
      }
      this.caseLoading = false
    } catch (err) {
      this.caseLoading = false
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async loadSupplierMore () {
    try {
      if (this.supplierLoading || this.supplierAlloaded) return
      this.supplierLoading = true
      let query = {
        currentPage: this.data.supplierPage,
        pageLines: this.data.pageSize,
      }
      if (this.data.keyword) query.data = this.data.keyword
      const { ResultSet } = await getSearchSupplier({ ...query })
      this.supplierAlloaded = !ResultSet.userData.data.length
      this.data.isSupplierEmpty = !ResultSet.userData.data.length
      this.setData({ isSupplierEmpty: this.data.isSupplierEmpty })
      if (ResultSet.userData.data.length) {
        this.data.supplierPage = this.data.supplierPage + 1
        this.data.supplierList.push(...ResultSet.userData.data)
        this.setData({
          supplierList: this.data.supplierList,
          supplierPage: this.data.supplierPage
        })
      }
      this.supplierLoading = false
    } catch (err) {
      this.supplierLoading = false
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async chooseMedia () {
    try {
      const { tempFiles } = await wx.$pro.chooseMedia({ count: 1, mediaType: 'image' })
      wx.showLoading({ title: '正在上传图片...' })
      const { fileUrl } = await this.uploadFile(tempFiles[0], 'tempFilePath')
      const { ResultSet } = await saveFile({ fileList: [{ fileUrl: fileUrl }] })
      wx.hideLoading()
      wx.$nav.navigateTo(`/pages/searchImage/index?fileId=${ResultSet.userData.fileIdList[0].fileId}&fileUrl=${ResultSet.userData.fileIdList[0].fileUrl}`)
    } catch (err) {
      wx.hideLoading()
      console.log(err)
    }
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  async getSearchHistory () {
    try {
      const { ResultSet } = await getSearchHistory()
      this.setData({
        historys: ResultSet.userData.history && ResultSet.userData.history.length ? ResultSet.userData.history : [],
        copyHistorys: ResultSet.userData.history && ResultSet.userData.history.length ? JSON.parse(JSON.stringify(ResultSet.userData.history)) : [],
        hotHistorys: ResultSet.userData.hotHistory && ResultSet.userData.hotHistory.length ? ResultSet.userData.hotHistory : [],
        copyHotHistorys: ResultSet.userData.hotHistory && ResultSet.userData.hotHistory.length ? JSON.parse(JSON.stringify(ResultSet.userData.hotHistory)) : []
      })
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getMaterialList () {
    try {
      let query = {
        currentPage: 1,
        pageLines: this.data.pageSize,
      }
      if (this.data.keyword) query.data = this.data.keyword
      const { ResultSet } = await getSearchMaterial({ ...query })
      this.materialLoading = false
      this.materialAlloaded = false
      if (ResultSet.userData.data.length) this.data.materialPage = 2
      this.data.isMaterialEmpty = ResultSet.userData.data.length && ResultSet.userData.data.length < this.data.pageSize
      this.setData({
        materialList: ResultSet.userData.data,
        materialPage: this.data.materialPage,
        materialNum: ResultSet.userData.materialNum,
        isMaterialEmpty: this.data.isMaterialEmpty
      })
      this.materialLoading = false
    } catch (err) {
      this.materialLoading = false
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getCaseList () {
    try {
      let query = {
        currentPage: 1,
        pageLines: this.data.pageSize,
      }
      if (this.data.keyword) query.data = this.data.keyword
      const { ResultSet } = await getSearchCase({ ...query })
      this.caseLoading = false
      this.caseAlloaded = false
      if (ResultSet.userData.data.length) this.data.casePage = 2
      this.data.isCaseEmpty = ResultSet.userData.data.length && ResultSet.userData.data.length < this.data.pageSize
      this.setData({
        caseList: ResultSet.userData.data,
        casePage: this.data.casePage,
        caseNum: ResultSet.userData.materialNum,
        isCaseEmpty: this.data.isCaseEmpty
      })
      this.caseLoading = false
    } catch (err) {
      this.caseLoading = false
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getSupplierList () {
    try {
      let query = {
        currentPage: 1,
        pageLines: this.data.pageSize,
      }
      if (this.data.keyword) query.data = this.data.keyword
      const { ResultSet } = await getSearchSupplier({ ...query })
      this.supplierLoading = false
      this.supplierAlloaded = false
      if (ResultSet.userData.data.length) this.data.supplierPage = 2
      this.data.isSupplierEmpty = ResultSet.userData.data.length && ResultSet.userData.data.length < this.data.pageSize
      this.setData({
        supplierList: ResultSet.userData.data,
        supplierPage: this.data.supplierPage,
        supplierNum: ResultSet.userData.materialNum,
        isSupplierEmpty: this.data.isSupplierEmpty
      })
      this.supplierLoading = false
    } catch (err) {
      this.supplierLoading = false
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  changeMaterial ({ detail }) {
    console.log(detail)
    let index = this.data.materialList.findIndex(row => row.materialCaseId === detail.materialCaseId)
    if (index > -1) {
      let changeKey = `list[${index}]`
      this.setData({
        [changeKey]: detail
      })
    }
  },
  async onLoad () {
    try {
      await this.getSearchHistory()
      const { screenWidth } = await wx.$pro.getSystemInfoSync()
      let query = this.createSelectorQuery()
      query.selectAll('.history-tag-item').boundingClientRect(rect => {
        let count = 0
        let idx= 0
        rect.forEach((item, index) => {
          if (item.left <= rect[0].left) {
            count++
            if (count === 3) {
              idx = index - 1
              this.setData({ historyMoreBtn: true, showHistoryMoreBtn: true, sliceIndex: idx })
            }
          }
        })
        if (idx > 0) {
          this.data.historys = this.data.copyHistorys.slice(0, idx)
          this.setData({historys: this.data.historys})
        } else {
          this.setData({historys: this.data.copyHistorys})
        }
      }).exec()
      query.selectAll('.hot-tag-item').boundingClientRect(rect => {
        let count = 0
        let idx = 0
        rect.forEach((item, index) => {
          if (item.left <= rect[0].left) {
            count++
            if (count === 3) {
              idx = index - 1
              this.setData({ hotMoreBtn: true, showHotMoreBtn: true, sliceHotIndex: idx })
            }
          }
        })
        if (idx > 0) {
          this.data.hotHistorys = this.data.copyHotHistorys.slice(0, idx)
          this.setData({hotHistorys: this.data.hotHistorys})
        } else {
          this.setData({hotHistorys: this.data.copyHotHistorys})
        }
      }).exec()
    } catch (err) {
      console.log(err)
    }
  }
})